package cn.amaake.magicplugin.nacos.module;

import cn.amaake.magicplugin.nacos.config.NacosConfig;
import cn.amaake.magicplugin.nacos.util.NacosUtils;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.ssssssss.magicapi.core.annotation.MagicModule;
import org.ssssssss.script.annotation.Comment;

import java.util.Map;

@MagicModule("nacosconfig")
public class NacosConfigModule {

    private ConfigService configService;

    private NacosConfig nacosConfig;

    public NacosConfigModule(ConfigService configService, NacosConfig nacosConfig){
        this.configService = configService;
        this.nacosConfig = nacosConfig;
    }

    @Comment("获取远程配置")
    public String getconfig(@Comment("key(配置key)")String key) throws NacosException {
        String config = configService.getConfig(nacosConfig.getDataId(), nacosConfig.getGroup(), nacosConfig.getTimeout());
        Map<String, Object> source = NacosUtils.toProperties(nacosConfig.getDataId(), nacosConfig.getGroup(), config, nacosConfig.getType().getType());
        String value = source.get(key).toString();
        return value;
    }

    @Comment("获取远程配置-根据文件类型")
    public String getconfig(@Comment("key(配置key)")String key,@Comment("配置文件类型")String configtype) throws NacosException {
        String config = configService.getConfig(nacosConfig.getDataId(), nacosConfig.getGroup(), nacosConfig.getTimeout());
        Map<String, Object> source = NacosUtils.toProperties(nacosConfig.getDataId(), nacosConfig.getGroup(), config, configtype);
        String value = source.get(key).toString();
        return value;
    }

    @Comment("获取远程配置")
    public String getconfig(@Comment("dataId(远程dataId)")String dataId, @Comment("group(远程group)")String group,@Comment("key(配置key)")String key) throws NacosException {
        String config = configService.getConfig(dataId, group, nacosConfig.getTimeout());
        Map<String, Object> source = NacosUtils.toProperties(dataId, group, config, nacosConfig.getType().getType());
        String value = source.get(key).toString();
        return value;
    }

    @Comment("获取远程配置-根据文件类型")
    public String getconfig(@Comment("dataId(远程dataId)")String dataId, @Comment("group(远程group)")String group,@Comment("key(配置key)")String key,@Comment("配置文件类型")String configtype) throws NacosException {
        String config = configService.getConfig(dataId, group, nacosConfig.getTimeout());
        Map<String, Object> source = NacosUtils.toProperties(dataId, group, config, configtype);
        String value = source.get(key).toString();
        return value;
    }

}
